﻿using Mina.Core.Session;
using Mina.Filter.Codec;
using Mina.Filter.Codec.Demux;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpIM.Http
{
    public class HttpResponseEncoder : IMessageEncoder<HttpResponse>
    {
        public void Encode(IoSession session, object message, IProtocolEncoderOutput output)
        {
            var resp = message as HttpResponse;
            if (resp != null)
            {
                this.Encode(session, resp, output);
            }
            else
            {
                var ctx = session.GetAttribute<HttpContext>(HttpRequestDecoder.httpContextAttributeName);
                var request = ctx.Request;
                var result = message as IHttpResult;
                if (result == null)
                {
                    resp = request.CreateResponse(500, $"can not convert type {message.GetType()} to {typeof(IHttpResult)}");
                }
                else
                {
                    resp.Body = result;
                }
                this.Encode(session, resp, output);
            }
            output.Flush();
        }

        public void Encode(IoSession session, HttpResponse response, IProtocolEncoderOutput output)
        {
            try
            {
                response.OutputResponse(output);
            }
            catch (Exception ex)
            {
                response = MessageHandler._httpServer.CreateErrorResponse(response.HttpContext, ex);
                response.OutputResponse(output);
            }
            finally
            {
                session.RemoveAttribute(HttpRequestDecoder.httpContextAttributeName);
            }
        }
    }
}
